<?php

namespace app\api\logic;

use app\common\model\UsersModel;
use app\common\basic\BasicLogic;
use app\common\service\JwtApiAuthService;
use app\common\cache\UserAccountSafeCache;

class LoginLogic extends BasicLogic
{

    protected $jwtAuth;

    public function __construct()
    {
        $this->jwtAuth = new JwtApiAuthService();
    }

    /**
     * 登录
     */
    public function login($params): array
    {
        // 获取当前时间
        $time = date("Y-m-d H:i:s", time());
        // 查找账户是否存在
        $user = UsersModel::where('account', $params['username'])->find();

        if (!$user) {
            // 用户名或密码不正确
            return ['error' => true, 'msg' => '用户名或者密码不正确'];
        }
        if ($user['disable'] == 1) {
            // 账户被禁用
            return ['error' => true, 'msg' => '账户被禁用'];
        }
        // 检查账户安全性
        $accountSafeCache = new UserAccountSafeCache();
        if (!$accountSafeCache->isSafe()) {
            // 账户不安全
            return ['error' => true, 'msg' => '失败次数太多，请稍后再试'];
        }

        // 验证密码
        if (createPassword($params['password'], $user->salt) !== $user->password) {
            $accountSafeCache->record();
            return ['error' => true, 'msg' => '用户名或者密码不正确'];
        }

        // 更新登录时间和IP
        $user->login_time = $time;
        $user->login_ip = request()->ip();
        $user->save();

        // 登录成功，准备返回的数据
        $data['user'] = [
            'id' => $user->id,
            'account' => $user->account,
            'avatar' => $user->avatar,

        ];
        $data['token'] = $this->jwtAuth->createToken(['id' => $user->id]);
        return ['error' => false, 'data' => $data];
    }

    /**
     * 注册
     */
    public function register($data)
    {
        $user = new UsersModel();
        $user->account = $data['username'];
        $salt = randomString(8,3);
        $user->password = createPassword($data['password'], $salt);
        $user->salt = $salt;
        $re = $user->save();
        if ($re) {
            return true;
        } else {
            return_error('保存失败！请重试');
        }
    }
}